package com.micro.school.system.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.common.security.utils.SecurityUtils;
import com.micro.school.system.api.RemoteEduService;
import com.micro.school.system.api.domain.vo.*;
import com.micro.school.system.api.model.LoginUser;
import com.micro.school.system.domain.StudentInfo;
import com.micro.school.system.domain.vo.StudentBatchLogVo;
import com.micro.school.system.mapper.StudentInfoMapper;
import com.micro.school.system.service.IBatchLogDetailService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.micro.school.system.mapper.BatchLogDetailMapper;
import com.micro.school.system.domain.BatchLogDetail;
import com.micro.school.system.domain.vo.BatchLogDetailVo;
import com.micro.school.system.convert.student.BatchLogDetailConvert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author rakic
 * @date 2025-08-05
 */
@Service
public class BatchLogDetailServiceImpl extends ServiceImpl<BatchLogDetailMapper,BatchLogDetail> implements IBatchLogDetailService
{
    @Autowired
    private BatchLogDetailMapper batchLogDetailMapper;

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Resource
    private RemoteEduService remoteEduService;
    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public BatchLogDetailVo selectBatchLogDetailById(Long id)
    {

        return batchLogDetailMapper.selectBatchLogDetailById(id, Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param batchLogDetailVo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<BatchLogDetailVo> selectBatchLogDetailList(BatchLogDetailVo batchLogDetailVo)
    {
        List<BatchLogDetailVo> batchLogDetailVos = batchLogDetailMapper.selectBatchLogDetailList(batchLogDetailVo);
        if (1 == SecurityContextHolder.getUserIdcardState()){
            batchLogDetailVos.forEach(vo -> {
                if (vo.getIdNumber() != null && vo.getIdNumber().length() > 8) {
                    String maskedIdNumber = vo.getIdNumber().substring(0, vo.getIdNumber().length() - 8) + "********";
                    vo.setIdNumber(maskedIdNumber);
                } else if (vo.getIdNumber() != null) {
                    vo.setIdNumber(vo.getIdNumber().replaceAll(".", "*"));
                }
            });
        }
        return batchLogDetailVos;
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param batchLogDetailVo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertBatchLogDetail(BatchLogDetailVo batchLogDetailVo)
    {
        BatchLogDetail batchLogDetail = BatchLogDetailConvert.toEntity(batchLogDetailVo);


        return batchLogDetailMapper.insert(batchLogDetail);

    }

    @Override
    public String insertBatchLogDetails(List<BatchLogDetailVo> batchLogDetailVos, StudentBatchLogVo batchLogVo) {
        StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (BatchLogDetailVo batchLogDetailVo : batchLogDetailVos) {
            BatchLogDetail batchLogDetail = BatchLogDetailConvert.toEntity(batchLogDetailVo);
            BatchLogDetailVo batchLogDetailVo1 = new BatchLogDetailVo();
            batchLogDetailVo1.setIdNumber(batchLogDetailVo.getIdNumber());
            batchLogDetailVo1.setStatus(1L);
            List<BatchLogDetailVo> batchLogDetailVos1 = batchLogDetailMapper.selectBatchLogDetailList(batchLogDetailVo1);
            if (batchLogDetailVos1 != null && batchLogDetailVos1.size() > 0){
                if (batchLogDetail.getStatus() == 1){
                    batchLogDetail.setStatus(2L);
                    batchLogDetail.setErrorMessage("该身份证号已存在！");
                    stringBuffer.append("该身份证号已存在！");
                }else{
                    stringBuffer.append(batchLogDetail.getErrorMessage());
                }
            }else {
                if (batchLogDetail.getStatus() == 2) {
                    stringBuffer.append(batchLogDetail.getErrorMessage());
                }
            }

            batchLogDetail.setSignTime(simpleDateFormat.format(new Date()));
            batchLogDetail.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
            batchLogDetailMapper.insertBatchLogDetail(batchLogDetail);
        }
        if (stringBuffer.isEmpty() && batchLogVo.getStatus() == 1) {
            for (BatchLogDetailVo batchLogDetailVo : batchLogDetailVos) {
                StudentInfo studentInfo = new StudentInfo();
                // 基本信息
                studentInfo.setName(batchLogDetailVo.getName());
                studentInfo.setIdNumber(batchLogDetailVo.getIdNumber());
                studentInfo.setPhone(batchLogDetailVo.getPhone());
                // 性别转换 (BatchLogDetailVo 中是 String，StudentInfo 中是 Long)
                if (batchLogDetailVo.getSex() != null) {
                    if ("男".equals(batchLogDetailVo.getSex())) {
                        studentInfo.setSex(1L); // 男
                    } else if ("女".equals(batchLogDetailVo.getSex())) {
                        studentInfo.setSex(0L); // 女
                    }
                }
                // 学院信息
                studentInfo.setCollegeId(batchLogDetailVo.getCollegeId());
                studentInfo.setCollegeName(batchLogDetailVo.getCollegeName());
                // 学历信息
                studentInfo.setEducationId(batchLogDetailVo.getEducationId());
                studentInfo.setEducation(batchLogDetailVo.getEducation());
                // 专业信息
                studentInfo.setMajorId(batchLogDetailVo.getMajorId());
                studentInfo.setMajorName(batchLogDetailVo.getMajorName());
                // 年级信息
                studentInfo.setGradeId(batchLogDetailVo.getGradeId());
                studentInfo.setGradeName(batchLogDetailVo.getGradeName());
                // 班级信息
                studentInfo.setClassName(batchLogDetailVo.getClassName());
                // 学制信息
                studentInfo.setSchoolSystem(batchLogDetailVo.getSchoolSystem());
                // 默认状态设置
                studentInfo.setSignStatus(1L); // 1预报名成功
                studentInfo.setGraduate(0L);   // 1在校
                studentInfo.setSealStatus(0L); // 0未封存
                studentInfo.setCreateTime(new Date());
                studentInfo.setUpdateTime(new Date());
                // 设置 tenantId
                studentInfo.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                studentInfo.setCompusId(Math.toIntExact(batchLogDetailVo.getCampusId()));
                studentInfo.setBranchName(batchLogDetailVo.getBranchName());
                studentInfo.setIsDel(0);
                studentInfo.setSignTime(new Date());
                studentInfoMapper.insertStudentInfo(studentInfo);
            }

        }
        return stringBuffer.toString();
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param batchLogDetailVo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateBatchLogDetail(BatchLogDetailVo batchLogDetailVo)
    {
        BatchLogDetail batchLogDetail = BatchLogDetailConvert.toEntity(batchLogDetailVo);
        return batchLogDetailMapper.updateBatchLogDetail(batchLogDetail);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteBatchLogDetailByIds(Long ids)
    {

        return batchLogDetailMapper.deleteBatchLogDetailByIds(ids, Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteBatchLogDetailById(Long id)
    {

        return batchLogDetailMapper.deleteBatchLogDetailById(id, Integer.parseInt(SecurityContextHolder.getUserTenantId()));
    }

    @Override
    public String insertBatchLogDetails1(List<BatchLogDetailVo> uploadVos, StudentBatchLogVo batchLogVo) {
        StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (BatchLogDetailVo batchLogDetailVo : uploadVos) {
            BatchLogDetail batchLogDetail = BatchLogDetailConvert.toEntity(batchLogDetailVo);
            BatchLogDetailVo batchLogDetailVo1 = new BatchLogDetailVo();
            batchLogDetailVo1.setIdNumber(batchLogDetailVo.getIdNumber());
            batchLogDetailVo1.setStatus(1L);
            List<BatchLogDetailVo> batchLogDetailVos1 = batchLogDetailMapper.selectBatchLogDetailList(batchLogDetailVo1);
            if (batchLogDetailVos1 != null && batchLogDetailVos1.size() > 0){
                if (batchLogDetail.getStatus() == 1){
                    batchLogDetail.setStatus(2L);
                    batchLogDetail.setErrorMessage("该身份证号已存在！");
                    stringBuffer.append("该身份证号已存在！");
                }else{
                    stringBuffer.append(batchLogDetail.getErrorMessage());
                }
            }else {
                if (batchLogDetail.getStatus() == 2) {
                    stringBuffer.append(batchLogDetail.getErrorMessage());
                }
            }
            batchLogDetail.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
            batchLogDetail.setSignTime(simpleDateFormat.format(new Date()));
            batchLogDetailMapper.insertBatchLogDetail(batchLogDetail);
        }
        if (stringBuffer.isEmpty() && batchLogVo.getStatus() == 1) {
            for (BatchLogDetailVo batchLogDetailVo : uploadVos) {

                SchoolCollegeVos schoolCollegeVos = new SchoolCollegeVos();
                schoolCollegeVos.setCollegeName(thoroughCleanString(batchLogDetailVo.getCollegeName().trim()));
                schoolCollegeVos.setDeleteFlag("0");
                R<List<SchoolCollegeVos>> listR = remoteEduService.checkCollege(schoolCollegeVos);
                if (listR.getData() != null && listR.getData().size() > 0) {
                    batchLogDetailVo.setCollegeId(listR.getData().get(0).getId());
                }

                SchoolGradeVos schoolGradeVos = new SchoolGradeVos();
                schoolGradeVos.setGrade(thoroughCleanString(batchLogDetailVo.getGradeName().trim()));
                schoolGradeVos.setDeleteFlag("0");
                schoolGradeVos.setStatus("1");
                R<List<SchoolGradeVos>> listGradeVo = remoteEduService.checkGrade(schoolGradeVos);
                if (listGradeVo.getData() != null && listGradeVo.getData().size() > 0) {
                    batchLogDetailVo.setGradeId(listGradeVo.getData().get(0).getId());
                }

                CollegeModelVos collegeModelVos = new CollegeModelVos();
                collegeModelVos.setModelName(thoroughCleanString(batchLogDetailVo.getEducation().trim()));
                collegeModelVos.setCollegeName(thoroughCleanString(batchLogDetailVo.getCollegeName().trim()));
                if (listR.getData() != null && listR.getData().size() > 0) {
                    collegeModelVos.setCampusId(listR.getData().get(0).getCampusId());
                }
                collegeModelVos.setDeleteFlag("0");
                collegeModelVos.setStatus("1");
                R<List<CollegeModelVos>> listR1 = remoteEduService.checkEducation(collegeModelVos);
                if (listR1.getData() != null && listR1.getData().size() > 0) {
                    batchLogDetailVo.setEducationId(listR1.getData().get(0).getId());
                }

                CollegeMajorVos collegeMajorVos = new CollegeMajorVos();
                collegeMajorVos.setCollegeIds(String.valueOf(listR.getData().get(0).getId()));
                collegeMajorVos.setMajorName(thoroughCleanString(batchLogDetailVo.getMajorName().trim()));
                collegeMajorVos.setDeleteFlag("0");
                collegeMajorVos.setStatus("1");
                R<List<CollegeMajorVos>> listR2 = remoteEduService.checkMajor(collegeMajorVos);
                if (listR2.getData() != null && listR2.getData().size() > 0) {
                    batchLogDetailVo.setMajorId(listR2.getData().get(0).getId());
                }

                SchoolCampusVos schoolCampusVos = new SchoolCampusVos();
                if (listR.getData() != null && listR.getData().size() > 0) {
                    schoolCampusVos.setId(listR.getData().get(0).getCampusId());
                    schoolCampusVos.setDeleteFlag("0");
                    schoolCampusVos.setStatus("1");
                    R<List<SchoolCampusVos>> listR3 = remoteEduService.checkCampus(schoolCampusVos);
                    if (listR3.getData() != null && listR3.getData().size() > 0) {
                        batchLogDetailVo.setCampusId(listR3.getData().get(0).getId());
                        batchLogDetailVo.setBranchName(listR3.getData().get(0).getCampusName());
                    }
                }


                StudentInfo studentInfo = new StudentInfo();
                // 基本信息
                studentInfo.setName(batchLogDetailVo.getName());
                studentInfo.setIdNumber(batchLogDetailVo.getIdNumber());
                studentInfo.setPhone(batchLogDetailVo.getPhone());
                // 性别转换 (BatchLogDetailVo 中是 String，StudentInfo 中是 Long)
                if (batchLogDetailVo.getSex() != null) {
                    if ("男".equals(batchLogDetailVo.getSex())) {
                        studentInfo.setSex(1L); // 男
                    } else if ("女".equals(batchLogDetailVo.getSex())) {
                        studentInfo.setSex(0L); // 女
                    }
                }
                // 学院信息
                studentInfo.setCollegeId(batchLogDetailVo.getCollegeId());
                studentInfo.setCollegeName(batchLogDetailVo.getCollegeName());
                // 学历信息
                studentInfo.setEducationId(batchLogDetailVo.getEducationId());
                studentInfo.setEducation(batchLogDetailVo.getEducation());
                // 专业信息
                studentInfo.setMajorId(batchLogDetailVo.getMajorId());
                studentInfo.setMajorName(batchLogDetailVo.getMajorName());
                // 年级信息
                studentInfo.setGradeId(batchLogDetailVo.getGradeId());
                studentInfo.setGradeName(batchLogDetailVo.getGradeName());
                // 班级信息
                studentInfo.setClassName(batchLogDetailVo.getClassName());
                // 学制信息
                studentInfo.setSchoolSystem(batchLogDetailVo.getSchoolSystem());
                // 默认状态设置
                studentInfo.setSignStatus(1L); // 1预报名成功
                studentInfo.setGraduate(1L);   // 1在校
                studentInfo.setSealStatus(0L); // 0未封存
                studentInfo.setCreateTime(new Date());
                studentInfo.setUpdateTime(new Date());
                // 设置 tenantId
                studentInfo.setTenantId(batchLogDetailVo.getTenantId());
                studentInfo.setCompusId(Math.toIntExact(batchLogDetailVo.getCampusId()));
                studentInfo.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                studentInfo.setIsDel(0);
                studentInfo.setBranchName(batchLogDetailVo.getBranchName());
                studentInfo.setSignTime(new Date());
                studentInfoMapper.insertStudentInfo(studentInfo);
            }

        }
        return stringBuffer.toString();
    }


    /**
     * 更彻底地清理字符串
     * @param str 原始字符串
     * @return 清理后的字符串
     */
    private String thoroughCleanString(String str) {
        if (str == null) return null;
        // 去除首尾空格，然后去除所有特殊字符，只保留字母、数字、中文字符、空格和常见符号
        if (str == null) return null;
        // 去除首尾空白字符，将中间的换行符、制表符等替换为空格，然后将多个空格合并为单个空格
        return str.trim()
                .replaceAll("[\\r\\n\\t]", " ")
                .replaceAll("\\s+", " ");
    }

}
